package com.hnchances.controller;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.google.common.collect.Maps;
import com.hnchances.pojo.dto.UserDTO;
import com.hnchances.pojo.entity.Result;
import com.hnchances.pojo.entity.User;
import com.hnchances.pojo.vo.UserVO;
import com.hnchances.properties.JwtProperties;
import com.hnchances.security.LoginUserDetails;
import com.hnchances.service.UserService;
import com.hnchances.util.JwtUtil;
import com.hnchances.util.RedisClient;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {

    private final static String SEC = "@#$fgaf%$#@@(##Ukldhg84";

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<User> register(@RequestBody UserDTO userDTO){
        userService.register(userDTO);
        return Result.ok();
    }

    @PostMapping("/update")
    public Result<User> update(@RequestBody User user){
        userService.update(user);
        return Result.ok();
    }

    @PostMapping("/login")
    public Result<User> login(String username, String password, HttpServletRequest request){

        /*
         * 登录前判断是否上次的登录未过期,如果未过期直接删除,重新登录生成新token
         */
        String token1 = request.getHeader("token");
        // 判断是否存在
        if (StringUtils.hasText(token1)){
            // 获取username
            String username1 = JWTUtil.parseToken(token1).getPayload("username").toString();
            // 判断这个username1是否为空
            if (StringUtils.hasText(username1)){
                // 删除token
                redisClient.del("login:token:"+token1);
            }
        }


        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证成功那么会有用户信息，否则为空
        if (Objects.isNull(authenticate)){
            return Result.error("用户名或密码错误");
        }
        // 用户信息
        LoginUserDetails principal = (LoginUserDetails) authenticate.getPrincipal();

        long currentTimeMillis = System.currentTimeMillis();

        Map<String,Object> map = Maps.newHashMap();
        map.put("username",principal.getUsername());
        map.put("exp",currentTimeMillis/1000+7*24*60*60);
        String token = JWTUtil.createToken(map, SEC.getBytes(StandardCharsets.UTF_8));

        String jsonStr = JSONUtil.toJsonStr(principal);
        redisClient.set("login:token:"+token,jsonStr,1000*60*60*24*7L);
        Map<String,Object> redis = Maps.newHashMap();
        redis.put("token",token);

        return Result.ok(redis);
    }

    @DeleteMapping("/del")
    public Result<User> del(@RequestParam Long id){
        userService.del(id);
        return Result.ok();
    }

    @GetMapping("/userinfo")
    public Result<User> getById(@RequestParam Long id){
        User user = userService.selectById(id);
        return Result.success(user);
    }
}
